package com.up.upzl.biz.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.up.upzl.base.config.WeixinUtil;
import com.up.upzl.biz.domain.PaiDianRecord;
import com.up.upzl.biz.domain.PaiDianRecord.Status;
import com.up.upzl.biz.service.paiDianRecordRepositorys;
import com.up.upzl.biz.service.impl.PaiDianRecordServiceImpl;

/**
 * 商铺控制器
 * 
 * @author joker
 *
 */
@Controller
@RequestMapping("/shop")
public class ShopController {

	private final Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private HttpServletResponse response;

	// 微信appid
	final String appid = "wxd3730802694fecf4";
	// 微信的appsecret秘钥
	final String appsecret = "f3e346607af09a2773c7b716865134b3";

	@Autowired
	private HttpSession session;

	@Autowired
	private PaiDianRecordServiceImpl paiDianRecordServiceImpl;

	@Autowired
	private paiDianRecordRepositorys paiDianRecordRepositorys;

	@RequestMapping("ok")
	public String login() {
		return "/login.html";
	}

	@RequestMapping("reference")
	public String description() {
		return "/description.html";
	}

	@RequestMapping("store")
	public String store() {
		return "/assignment.html";
	}

	/**
	 * 获取微信授权地址
	 * 
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("wx")
	public void wx() throws Exception {
		String authUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
		System.out.println("授权地址模板:" + authUrl);

		// 微信网页授权地址，这个是回调地址，回调地址必须在授权地址的下级
		// http://h5.zpb.youpuchina.com
		String callbackUrl = "http://h5.zpb.youpuchina.com/shop/openid";

		log.info("回调地址:{}", callbackUrl);

		authUrl = authUrl.replace("APPID", appid);
		authUrl = authUrl.replace("REDIRECT_URI", URLEncoder.encode(callbackUrl, "UTF-8"));
		authUrl = authUrl.replace("SCOPE", "snsapi_base");

		System.out.println("真实授权地址:" + authUrl);

		response.sendRedirect(authUrl);
	}

	/**
	 * 通过微信的授权地址获取微信的openid
	 * 
	 * @param response
	 * @param request
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("openid")
	public String openid() throws Exception {
		System.out.println("收到回调请求");

		String code = request.getParameter("code");
		String state = request.getParameter("state");

		System.out.println("授权码:" + code);
		System.out.println("state:" + state);

		// 通过code获取
		String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

		accessTokenUrl = accessTokenUrl.replace("APPID", appid);
		accessTokenUrl = accessTokenUrl.replace("SECRET", appsecret);
		accessTokenUrl = accessTokenUrl.replace("CODE", code);

		System.out.println("通过code换取用户openid地址:" + accessTokenUrl);

		String result = WeixinUtil.httpRequest(accessTokenUrl, "GET", null);
		System.out.println("获取用户openid结果:" + result);

		String openid = JSONObject.parseObject(result).getString("openid");
		session.setAttribute("openid", openid);
		System.out.println("===>openid:" + openid);
		return "/assignment.html";
	}

	@RequestMapping("recordd")
	public String paidian(Model model) {
		try {
			// 获取拍店人手机号码
			String phone = session.getAttribute("phone").toString();
			List<PaiDianRecord> dsh = paiDianRecordRepositorys.findByPhoneAndStatusOrderByIdDesc(phone,
					PaiDianRecord.Status.待审核);
			List<PaiDianRecord> ytg = paiDianRecordRepositorys.findByPhoneAndStatusOrderByIdDesc(phone,
					PaiDianRecord.Status.已通过);
			List<PaiDianRecord> wtg = paiDianRecordRepositorys.findByPhoneAndStatusOrderByIdDesc(phone,
					PaiDianRecord.Status.未通过);
			model.addAttribute("dsh", dsh);
			model.addAttribute("ytg", ytg);
			model.addAttribute("wtg", wtg);

		} catch (Exception e) {
			log.error("用户session获取为空，拍店信息读取异常");
		}

		return "/record.html";
	}

	/**
	 * 图片上传
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	public String upload(@RequestParam("file_head") MultipartFile[] files, HttpServletRequest request,
			HttpSession session, Model model) {
		String phone = "";
		try {
			// 获取拍店人的手机号码
			phone = session.getAttribute("phone").toString();
		} catch (Exception e) {
			log.error("获取拍店人手机号号码失败");
		}
		// 获取店主手机号码
		String ipone = request.getParameter("phone");
		PaiDianRecord paiDianRecord = new PaiDianRecord();
		String msg = request.getParameter("positioning");
		paiDianRecord.setDiqu(msg);

		try {

			String jingwei = request.getParameter("jingwei");
			log.info("获取到的经纬度：{}", jingwei);
			String[] xy = jingwei.split(",");// 使用字符串切割
			paiDianRecord.setLocationX(xy[0]);
			paiDianRecord.setLocationY(xy[1]);
		} catch (Exception e) {
			log.error("=========>" + "截取经纬度失败");

		} finally {
			paiDianRecord.setStatus(Status.待审核);
		}
		// 图片个数
		if (files.length > 0) {
			// 获取服务器的文件下载路径

			System.out.println("个数为：" + files.length);
			String realPath = "/opt/img";

			// 路径地址
			String Path = realPath;
			File filee = new File(Path);
			if (!filee.isDirectory()) {
				filee.mkdirs();
			} else {
				log.info("文件夹已存在");
			}

			List<String> imgStrs = new ArrayList<>(files.length);

			for (MultipartFile file : files) {
				String orgName = file.getOriginalFilename();
				System.out.println(orgName);
				// 判断文件名字是否为空
				if (orgName != null && !orgName.equals("")) {
					String fileName = UUID.randomUUID() + orgName;
					File tempFile = new File(Path + "/" + fileName);
					// path = /opt/img/2018-03-29
					// fileName = 文件名字
					String phString = Path + "/" + fileName;
					try {
						// tempFile =
						// /opt/img/2018-03-29/958e848c-d96a-40c4-829a-f2752730d0a799C564B2-BC2F-4921-AF6B-99EB6FC2E76A.png
						file.transferTo(tempFile);
					} catch (IllegalStateException e) {
						log.error("上传图片异常");
						e.printStackTrace();
					} catch (IOException e) {
						log.error("上传图片IO异常");
						e.printStackTrace();
					}
					imgStrs.add(phString);
				}
			}

			// 保存拍店人手机号码
			paiDianRecord.setPhone(phone);
			// 保存店主手机号码
			paiDianRecord.setIpone(ipone);
			String openid = session.getAttribute("openid").toString();
			paiDianRecord.setWechatId(openid);

			for (int i = 0; i < imgStrs.size(); i++) {
				String imageStr = imgStrs.get(i);

				if (i == 0) {
					paiDianRecord.setImg0(imageStr);
				} else if (i == 1) {
					paiDianRecord.setImg1(imageStr);
				} else if (i == 2) {
					paiDianRecord.setImg2(imageStr);
				} else if (i == 3) {
					paiDianRecord.setImg3(imageStr);
				} else if (i == 4) {
					paiDianRecord.setImg4(imageStr);
				} else if (i == 5) {
					paiDianRecord.setImg5(imageStr);
				} else if (i == 6) {
					paiDianRecord.setImg6(imageStr);
				} else if (i == 7) {
					paiDianRecord.setImg7(imageStr);
				}
			}
			paiDianRecord.setCreateTime();
			paiDianRecordServiceImpl.saveAndFlush(paiDianRecord);

			try {
				// 获取拍店人手机号码 phone
				phone = session.getAttribute("phone").toString();
			} catch (Exception e) {
				log.error("用户身份未登陆，无法获取拍店信息");
			}

			List<PaiDianRecord> dsh = paiDianRecordRepositorys.findByPhoneAndStatusOrderByIdDesc(phone,
					PaiDianRecord.Status.待审核);
			List<PaiDianRecord> ytg = paiDianRecordRepositorys.findByPhoneAndStatusOrderByIdDesc(phone,
					PaiDianRecord.Status.已通过);
			List<PaiDianRecord> wtg = paiDianRecordRepositorys.findByPhoneAndStatusOrderByIdDesc(phone,
					PaiDianRecord.Status.未通过);
			model.addAttribute("dsh", dsh);
			model.addAttribute("ytg", ytg);
			model.addAttribute("wtg", wtg);
		}
		return "/assignment.html";

	}

	@RequestMapping("/imgstream")
	public void IO(String file) throws IOException {
		// 读取本地图片输入流
		FileInputStream inputStream = new FileInputStream(new File(file));
		int i = inputStream.available();
		// byte数组用于存放图片字节数据
		byte[] buff = new byte[i];
		inputStream.read(buff);
		// 记得关闭输入流
		inputStream.close();
		// 设置发送到客户端的响应内容类型
		response.setContentType("image/*");
		OutputStream out = response.getOutputStream();
		out.write(buff);
		// 关闭响应输出流
		log.info("======>" + "访问到了");
		out.close();
	}

	/**
	 * 判断店主信息是否重复
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("is")
	public String is() {
		String ipone = request.getParameter("ipone");
		List<PaiDianRecord> paiDianRecords = paiDianRecordRepositorys.findByipone(ipone);
		if (paiDianRecords != null) {
			// 重复提交返回0
			return "0";
		} else {
			return "1";
		}
	}

	@RequestMapping("record")
	public String record() {
		return "record";
	}

	@RequestMapping("/callback")
	public String callback(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		System.out.println("收到回调请求");

		String code = request.getParameter("code");
		String state = request.getParameter("state");

		System.out.println("授权码:" + code);
		System.out.println("state:" + state);

		// 通过code获取
		String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

		accessTokenUrl = accessTokenUrl.replace("APPID", appid);
		accessTokenUrl = accessTokenUrl.replace("SECRET", appsecret);
		accessTokenUrl = accessTokenUrl.replace("CODE", code);

		System.out.println("通过code换取用户openid地址:" + accessTokenUrl);

		String result = WeixinUtil.httpRequest(accessTokenUrl, "GET", null);
		System.out.println("获取用户openid结果:" + result);

		String openid = JSONObject.parseObject(result).getString("openid");

		System.out.println("===>openid:" + openid);

		return "";
	}

}
